package com.design_patterns.iterator.v3;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-09-01 20:53
 **/
public class LinkedList_ implements Collection_ {
    private Node head = null;
    private Node tail = null;
    private int size = 0;

    public Integer size() {
        return size;
    }

    public LinkedList_ add(Object object) {
        Node node = new Node(object);
        node.next = null;
        if (head == null) {
            head = node;
            tail = node;
        }
        tail.next = node;
        tail = node;
        size++;
        return this;
    }


    @Override
    public Iterator_ iterator() {
        return new LinkedListIterator();
    }

    class Node {
        private Object element;
        private Node next;

        public Node(Object element) {
            this.element = element;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "element=" + element +
                    '}';
        }
    }

    class LinkedListIterator implements Iterator_ {
        private Node currentHeader = head;

        @Override
        public boolean hasNext() {
            if (currentHeader == head && currentHeader != null) {
                return true;
            }
            return currentHeader != null;
        }

        @Override
        public Object next() {
            Node next = currentHeader;
            currentHeader = currentHeader.next;
            return next;
        }
    }

}
